{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Chapter 8: Customizing Functions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Apply" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This instance happens when you want to perform more complex calculations on your data rather than addind or substracting two columns." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Things of such kind might prevent you from wrting a for loop to iterate over a whole column for instance" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/home/rockefeller/.local/lib/python3.9/site-packages/pandas/core/arrays/masked.py:64: UserWarning: Pandas requires version '1.3.2' or newer of 'bottleneck' (version '1.2.1' currently installed).\n", " from pandas.core import (\n" ] } ], "source": [ "import pandas as pd" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "def my_function():\n", " # indent 4 spaces\n", " # function code\n", " pass" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "def my_sq(x):\n", " \"\"\"squares a given value\n", " \"\"\"\n", " return x ** 2" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "my_sq(2)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "16" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "my_sq(4)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "def avg_2(x, y):\n", " \"\"\"calculates average between 2 numbers\n", " \"\"\"\n", " return (x + y) / 2.0" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "15.0" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "avg_2(10, 20)" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "df1 = pd.DataFrame({\n", " \"A\": [5,10,15],\n", " \"B\": [3,6,9]\n", " })" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", " | A | \n", "B | \n", "
---|---|---|
0 | \n", "5 | \n", "3 | \n", "
1 | \n", "10 | \n", "6 | \n", "
2 | \n", "15 | \n", "9 | \n", "